package cn.xiaoliu.pay.controller;

import cn.xiaoliu.order.domain.AdoptOrder;
import cn.xiaoliu.order.domain.ProductOrder;
import cn.xiaoliu.order.service.IAdoptOrderService;
import cn.xiaoliu.order.service.IProductOrderService;
import cn.xiaoliu.pay.config.AlipayConfig;
import cn.xiaoliu.pay.constants.AlipayConstants;
import cn.xiaoliu.pay.domain.AlipayInfo;
import cn.xiaoliu.pay.domain.PayBill;
import cn.xiaoliu.pay.service.IAlipayInfoService;
import cn.xiaoliu.pay.service.IPayBillService;
import cn.xiaoliu.quartz.constant.JobConstants;
import cn.xiaoliu.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IAdoptOrderService adoptOrderService;
    @Autowired
    private IQuartzService quartzService;
    @Autowired
    private IProductOrderService productOrderService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request){

        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            //获取订单唯一编号
            String unionPaySn = params.get("out_trade_no");
            PayBill payBill = payBillService.loadByUnionPaySn(unionPaySn);
            if (payBill != null){
                AlipayInfo info = alipayInfoService.getByShopId(payBill.getShop_id());
                //签名认证
                boolean signVerified = AlipaySignature.rsaCheckV1(
                        params,
                        info.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名

                if(signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no = request.getParameter("out_trade_no");

                    //支付宝交易号
                    String trade_no = request.getParameter("trade_no");

                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if(trade_status.equals("TRADE_FINISHED")){

                    }else if (trade_status.equals("TRADE_SUCCESS")){
                        //1.修改支付订单状态为已支付，修改时间
                        payBill.setState(1);//0是待支付  1已经支付   -1是取消
                        payBill.setUpdateTime(new Date());
                        payBillService.update(payBill);
                        //2.查询支付流水
                        //3.查询对应的业务订单，并且修改订单状态
                        String jobName = "";
                        if (AlipayConstants.BUSINESS_TYPE_ADOPT.equals(payBill.getBusinessType())){
                            AdoptOrder order = adoptOrderService.queryById(payBill.getBusinessKey());
                            order.setState(1);//1为待发货
                            adoptOrderService.update(order);
                            jobName = JobConstants.TIME_OUT_ADOPT_LAST_PAY + order.getId();
                        }else if (AlipayConstants.BUSINESS_TYPE_PRODUCT.equals(payBill.getBusinessType())){
                            ProductOrder productOrder = productOrderService.queryById(payBill.getBusinessKey());
                            productOrder.setState(1);//1为待发货
                            productOrderService.update(productOrder);
                            jobName = JobConstants.TIME_OUT_PRODUCT_LAST_PAY + productOrder.getId();
                        }
                        //@购买成功取消定时器
                        quartzService.removeJob(jobName);
                    }

                }else {//验证失败

                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

}
